<template>
	<el-dialog :title="$t('game.config.betting.dialog.edit')" width="800px" :visible.sync="dialogVisible"
	           @close="$emit('update:visible', false)"
	           :fullscreen="fullscreen" :class="{'fullscreen': fullscreen}">
		<vue-simplebar>
			<div class="pr-12">
				<el-form :model="dataCache" label-width="85px">

					<el-form-item :label="$t('game.setting.game.name')"
					              :error="Boolean(msg.errors['game_id']) ? msg.errors['game_id'][0] : ''" required>
						<component-page-game-option v-model="dataCache.game_id" :multiple="false"
						                            :disabled="data != null" class="block"
						                            @change="getBetStatus"></component-page-game-option>
					</el-form-item>


					<el-form-item :label="$t('game.config.currency.type')"
					              :error="Boolean(msg.errors['bet_type']) ? msg.errors['bet_type'][0] : ''" required>
						<component-page-loading :status="betStatus" @reload="getBetStatus"
						                        v-if="betStatus != 'dle'">
                        </component-page-loading>
						<el-select :placeholder="$t('game.config.currency.type')" v-else
						           :disabled="!bet_status" clearable
						           v-model="dataCache.config.globals.bet_type" class="block">
							<el-option v-for="(item, index) in $t('game.data.settlement.bet_type')" :key="index"
							           :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item :label="$t('platform.config.betting.config.gear')" :error="error_config_globals_bet"
					              required>
						<el-row class="mb-3" v-for="(bet, i) in dataCache.config.globals.bet" :key="i">
							<el-col :span="4">
								<div v-if="dataCache.config.globals.bet[i].currency != '_USD'">
									<component-page-loading :status="currencyListStatus" @reload="getCurrencyList"
									                        v-if="currencyListStatus != 'dle'"></component-page-loading>
									<el-select :placeholder="$t('game.setting.currency.name')" filterable clearable
									           v-model="dataCache.config.globals.bet[i].currency" class="block" v-else>
										<el-option v-for="item in currencyList" :key="item.currency"
										           :label="item.currency" :value="item.currency"></el-option>
									</el-select>
								</div>
								<el-input :title="$t('platform.config.betting.config.virtual')" :disabled="true"
								          :placeholder="$t('platform.config.betting.config.virtual')" v-else></el-input>
							</el-col>
							<el-col :span="17" class="pl-2">
								<el-input :placeholder="$t('platform.config.betting.config.gear')"
								          v-for="(item, j) in dataCache.config.globals.bet[i].gear" :key="j"
								          class="mini"
								          type="number"
								          v-model.number="dataCache.config.globals.bet[i].gear[j]"></el-input>
								<el-button class="ml-1" size="small" icon="el-icon-close" circle
								           @click="removeItemOrAdd(dataCache.config.globals.bet[i].gear, dataCache.config.globals.bet[i].gear.length - 1, null)"></el-button>
								<el-button class="ml-1" size="small" icon="el-icon-plus" circle
								           @click="addItem(dataCache.config.globals.bet[i].gear,null)"></el-button>
							</el-col>
							<el-col :span="3" class="text-right">
								<el-button size="small"
								           @click="removeItemOrAdd(dataCache.config.globals.bet, i, betItem)">
									{{ $t('action.delete') }}
								</el-button>
								<el-button size="small"
								           @click="addItem(dataCache.config.globals.bet, dataCache.config.globals.bet[i])"
								           v-if="dataCache.config.globals.bet[i].currency != '_USD'">
									{{ $t('action.copy') }}
								</el-button>
							</el-col>
						</el-row>
						<el-button size="small" @click="addItem(dataCache.config.globals.bet,betItem)">
							{{ $t('action.add') }}
						</el-button>
						<el-button size="small" @click="addVirtualCurrency" v-if="!isExistVirtualCurrency">
							{{ $t('action.add') }} {{ $t('platform.config.betting.config.virtual') }}
						</el-button>
					</el-form-item>

				</el-form>
			</div>
		</vue-simplebar>
		<div slot="title" class="flex justify-between items-center pr-8">
			<div>{{ $t('game.config.betting.dialog.edit') }}</div>
			<div class="operation-icon">
				<i class="el-icon-full-screen float-right" @click="fullscreen = !fullscreen"></i>
			</div>
		</div>
		<div slot="footer">
			<el-button @click="dialogVisible = false">{{ $t('action.cancel') }}</el-button>
			<el-button type="primary" @click="onSubmit">{{ $t('action.save') }}</el-button>
		</div>
	</el-dialog>
</template>

<script>
export default {
	name: "ItemEdit",
	props: ['visible', 'org', 'data','btntype'],
	data() {
		return {
			dialogVisible: false,
			currencyListStatus: 'dle',
			betStatus: 'dle',
			bet_status: null,
			currencyList: [],
			dataCache: {
				plat_code: '',
				game_id: '',
				config: {
					globals: {
						bet_type: null,
						bet: [],
					}
				},
			},
			dataInit: {},
			betItem: {
				'currency': '',
				gear: [null, null, null, null, null, null]
			},
			msg: {
				code: 200,
				message: '',
				errors: {},
			},
			fullscreen: false,
		}
	},
	computed: {
		error_config_globals_bet: function () {
			for (let key in this.msg.errors) {
				if (_.startsWith(key, 'config.globals.bet')) {
					return this.msg.errors[key][0];
				}
			}
		},

		isExistVirtualCurrency: function () {
			if (this.dataCache == null ||
				this.dataCache.config == null ||
				this.dataCache.config.globals == null ||
				this.dataCache.config.globals.bet == null) {
				return true;
			}
			for (let item of this.dataCache.config.globals.bet) {
				if (item.currency == '_USD') {
					return true;
				}
			}
			return false;
		},

	},
	watch: {
		visible: function (n, o) {
			if (n) {
				// 初始化参数
				this.initData();
				// 显示模态框
				this.dialogVisible = n;
				// 获取币种列表
				this.getCurrencyList();
			}
		}
	},
	created() {
		this.dataInit = _.cloneDeep(this.dataCache);
	},
	methods: {
		//  获取选中游戏的 bet_status
		getBetStatus() {
			// this.dataCache.config.globals.bet_type = null;
			this.betStatus = 'loading';

			// 发起 Ajax 请求
			axios.get('/game/config/betting/getGameDetails', {
				params: {game_id: this.dataCache.game_id}
			}).then(response => {
				// 处理响应数据

				if (response.data.resp_msg.code == 200) {
					// 源系统
					// 新增时初始化投注类型
					this.bet_status = response.data.resp_data.bet_status;

					if (this.dataCache.config.globals.bet_type == null || this.bet_status == 0) {
                        this.dataCache.config.globals.bet_type = 1;
                    }
					// console.log(this.dataCache.config.globals.bet_type);
					// console.log(this.dataCache.config.globals.bet_type);

					this.betStatus = 'dle';
				} else {
					this.betStatus = 'error';
				}
				console.log(this.dataCache,"进来了哦---",response)
			})
		},


		// 获取币种列表
		getCurrencyList() {
			this.currencyListStatus = 'loading';
			axios.get('/platform/config/betting/getCurrencyList', {
				params: {plat_code: this.org.code}
			}).then((response) => {
				if (response.data.resp_msg.code == 200) {
					this.currencyList = response.data.resp_data;
					this.currencyListStatus = 'dle';
				} else {
					this.$message({
						type: 'error',
						message: response.data.resp_msg.message,
						showClose: true
					});
					this.currencyListStatus = 'error';
				}
			})
		},
		initMsg() {
			this.msg.code = 200;
			this.msg.message = '';
			this.msg.errors = {};
		},
		initData() {
			this.initMsg();
			if (this.data == null) {
				// 新增
				this.dataCache = _.cloneDeep(this.dataInit);
				this.dataCache.plat_code = this.org.code;
			} else {
				// 编辑
				this.dataCache = _.cloneDeep(this.data);
				this.dataCache.game_id = this.data.game_id;
				this.dataCache.plat_code = this.org.code;
                if(this.dataCache.game_id){
                    this.getBetStatus()
                }
				// 初始化是否
				if (this.dataCache.config == null) {
					this.$set(this.dataCache, 'config', {});
				} else if (Array.isArray(this.dataCache.config)) {
					this.$set(this.dataCache, 'config', {});
				}
				if (this.dataCache.config.globals == null) {
					this.$set(this.dataCache.config, 'globals', {});
				} else if (Array.isArray(this.dataCache.config.globals)) {
					this.$set(this.dataCache.config, 'globals', {});
				}
				if (this.dataCache.config.globals.bet == null) {
					this.$set(this.dataCache.config.globals, 'bet', []);
				}

				if (this.bet_status == null) {
					this.bet_status = 0;
				}
				if (this.dataCache.config.globals.bet_type == null) {
					this.$set(this.dataCache.config.globals, 'bet_type', 1);
				}

				console.log(this.data,this.dataCache)
			}
		},
		addVirtualCurrency() {
			this.dataCache.config.globals.bet.unshift(
				{...this.betItem, ...{currency: '_USD'}}
			);
		},

		addItem(configs, item) {
			this.$nextTick(function () {
				configs.push(_.cloneDeep(item));
			});
		},
		removeItem(configs, index) {
			configs.splice(index, 1);
		},
		removeItemOrAdd(configs, index, item) {
			this.removeItem(configs, index);
			if (!configs.length) {
				this.addItem(configs, item);
			}
		},
		onSubmit() {
			this.initMsg();
			// loading 状态 start
			let loading = this.$loading();
			// 保存数据
			console.log(this.dataCache)
			axios.post('/platform/config/betting/save', this.dataCache).then((response) => {
				// loading 状态 close
				loading.close();
				// 逻辑处理
				if (response.data.resp_msg.code == 200) {
					this.$message({
						type: 'success',
						message: this.$t('messages.succeeded', {status: this.$t('action.save')}),
						showClose: true
					});
					this.dialogVisible = false;
					// 广播事件到父组件
					this.$emit('edit');
				} else if (_.includes([42000, 44202], response.data.resp_msg.code)) {
					this.$message({
						type: 'error',
						message: response.data.resp_msg.message,
						showClose: true
					});
					this.msg = response.data.resp_msg;
				} else {
					this.$message({
						type: 'error',
						dangerouslyUseHTMLString: true,
						message: this.$t('messages.failed', {status: this.$t('action.save')}) + `<div class="mt-2">${response.data.resp_msg.message}</div>`,
						showClose: true
					});
				}
			})
		},
	}
}
</script>

<style scoped>
::v-deep .el-dialog__body {
	padding-top: 15px;
	padding-bottom: 15px;
	height: 600px;
}

::v-deep.fullscreen .el-dialog__body {
	height: calc(100vh - 125px);
}
</style>
